package com.pitaya.winwine.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.baidu.bae.api.factory.BaeFactory;
import com.baidu.bae.api.image.BaeImageService;
import com.baidu.bae.api.image.VCode;
import com.pitaya.framework.common.MailUtils;
import com.pitaya.framework.common.StringUtils;
import com.pitaya.winwine.domain.User;
import com.pitaya.winwine.repository.TagRepository;
import com.pitaya.winwine.repository.UserRepository;
import com.pitaya.winwine.service.UserService;

@Controller
@RequestMapping
public class IndexAction {
	
	private static final Log log = LogFactory.getLog(IndexAction.class);

	@Autowired
	private UserService userService;

	@Autowired
	private UserRepository userRepository;
	
	@Autowired
	private TagRepository tagRepository;
	
	@RequestMapping
	public String index() {
		return "redirect:/vintry";
	}

	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String toRegister() {
		return "register";
	}

	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public String doRegister(HttpSession session, User user) {
		user.setType(User.TYPE_USER);
		user.setStatus(User.STATUS_ENABLED);
		userService.save(user);
		if (user.getId() != null)  {
			session.setAttribute("user", user);
			return "redirect:/user/tag/choose";
	    }else {
	    	log.error("用户注册失败!");
		    throw new RuntimeException();
	    }
	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView toLogin(String redirectUrl) {
	    return new ModelAndView("login", "redirectUrl", redirectUrl);
	}
	
	@RequestMapping(value="/login", method=RequestMethod.POST)
	public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response,
			  User user, String redirectUrl) {
		user = userService.login(request, response, user);
		if (user != null) {
		  	StringBuilder url = new StringBuilder();
		 	url.append("redirect:");
			if (StringUtils.isNotBlank(redirectUrl)) {
				url.append(redirectUrl);
			}else {
				url.append("/");
		   	}
			return new ModelAndView(url.toString());
		}
		Map model = new HashMap();
		model.put("errorMsg", "用户名或密码错误");
		model.put("redirectUrl", redirectUrl);
		return new ModelAndView("/login", model);
	}
	  
	@RequestMapping("/logout")
	public String doLogout(HttpServletRequest request, HttpServletResponse response) {
		request.getSession().invalidate();
	    Cookie cookie = new Cookie("wineu", null);
	    cookie.setMaxAge(0);
	    response.addCookie(cookie);
	    cookie = new Cookie("winep", null);
	    cookie.setMaxAge(0);
	    response.addCookie(cookie);
	    return "redirect:/login";
	}
	
	@RequestMapping(value = "/forgot", method = RequestMethod.GET)
	public String toForgotPage() {
	    return "forgot";
	}
	
	@RequestMapping(value = "/forgot", method = RequestMethod.POST)
	public ModelAndView forgot(User user) {
		String email = user.getEmail();
		user = userRepository.findByUsername(user.getUsername());
		if(user != null && user.getEmail().equals(email)) {
			String newPass = StringUtils.getRandomStr(8);
			user.setPassword(DigestUtils.md2Hex(newPass));
			StringBuilder msg = new StringBuilder();
			msg.append("---------------------------------------------------------------<br/>")
				.append("密码找回<br/>")
		        .append("---------------------------------------------------------------<br/>")
		        .append("<br/>您的新密码为：<strong>").append(newPass)
		        .append("</strong>，您可以登录网站后修改！");
			if(MailUtils.sendHtmlEmail("密码找回 - 红酒会", msg.toString(), new String[] { user.getEmail()})) {
				MailUtils.sendHtmlEmail("密码找回 - 红酒会", msg.toString(), new String[] { user.getEmail()});
				this.userRepository.save(user);
				return new ModelAndView("redirect:/forgot/finish");
			}
		}
		return new ModelAndView("forgot", "errorMsg", "信息填写错误！");
	}
	
	@RequestMapping(value = "/forgot/finish")
	public String finishedForgot() {
		return "forgot_finish";
	}
	
	@ResponseBody
	@RequestMapping("/verify")
	public String verify(HttpSession session) {
		BaeImageService baeImageService = BaeFactory.getBaeImageService();
		VCode code = new VCode();
		code.setLen(4);
		Map<String, String> data = baeImageService.generateVCode(code);
		session.setAttribute("vcode_secret", data.get("secret"));
		return data.get("imgurl");
	}

	@ResponseBody
	@RequestMapping("/validate/{type}")
	public boolean validateRegister(HttpServletRequest request, @PathVariable("type") String type, String str) {
		if("verify".equals(type)) {
			return true;
		}else if("username".equals(type)) {
			return userRepository.findByUsername(str) == null;
		}else {
			return userRepository.findByEmail(str) == null;
		}
	}

	@RequestMapping("/header")
	public ModelAndView header(HttpSession session) {
		Map model = new HashMap();
		User user = (User) session.getAttribute("user");
		if (user != null) {
			/*
			 model.put("unreadEventCount", Integer.valueOf(this.eventService
			 .getUnreadCount(user.getId().intValue())));
			 */
			// TODO
		}
		return new ModelAndView("header", model);
	}
}
